//
//  CQComposeController.swift
//  weibo
//
//  Created by chengqiang on 16/7/29.
//  Copyright © 2016年 chengqiangBiaodashi. All rights reserved.
//

import UIKit

class CQComposeController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = DefaultBKGColor
        
        self.setupUI()
        
        //监听键盘的弹出和退下
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //呼出键盘
        textView.becomeFirstResponder()
    }
    func willChangeFrame(notification:NSNotification)  {
        // 动画事件
        let duration: NSTimeInterval = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        //键盘最终的位置
        let endFrame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        //计算toolBar底部的约束
        let bottonValue = -(UIScreen.height()-endFrame.origin.y)
        
        
        toolBar.snp_makeConstraints { (make) in
            make.bottom.equalTo(self.view).offset(bottonValue)
        }
        UIView.animateWithDuration(duration) { ()->Void in
            //强制更新View和其子控件的frame   根据约束更新
            self.view.layoutIfNeeded()
        }
    }
    
    //设置界面
    private func setupUI(){
        setupTextView()
        setupNavigationBar()
        setToolBar()
    }
    
    //设置toolBar
    private func setToolBar(){
        self.view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) in
            make.leading.trailing.bottom.equalTo(self.view)
        }
        
        let itemSettings = [
        ["imageName":"compose_toolbar_picture","action":"picture"],
        ["imageName":"compose_trendbutton_background","action":"trend"],
        ["imageName":"compose_mentionbutton_background","action":"mention"],
        ["imageName":"compose_emoticonbutton_background","action":"emoticon"],
        ["imageName":"compose_add_background","action":"add"]
        ]
        
        toolBar.items = [UIBarButtonItem]()
        for (index,dict) in itemSettings.enumerate() {
            let imageName = dict["imageName"]!
            let action = dict["action"]
            let barButtonItem = UIBarButtonItem(imageName: imageName, target: self, action: Selector(action!),tag:index)
            toolBar.items?.append(barButtonItem)
            //弹簧
            let flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            toolBar.items?.append(flexible)
        }
        //删除最后一个弹簧
        toolBar.items?.removeLast()
    }
    
    //MARK:-toolbar按钮点击事件
    
    @objc private func picture() {
        print("图片")
    }
    
    @objc private func trend() {
        print("#")
    }
    
    @objc private func mention() {
        print("@")
    }
    
    @objc private func emoticon() {
        print("表情")
    }
    
    @objc private func add() {
        print("+")
    }
    
    
    //设置textView
    private func setupTextView(){
        self.view.addSubview(textView)
        
        textView.snp_makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
    }
    
    
    //设置导航栏按钮
    private func setupNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        setupTitle()
    }
    //设置title
    private func setupTitle(){
        let prefix = "发微博"
        
        if let screen_name = CQUserViewModel.shareduserAccountViewModel.userAccount?.screen_name{
            let cont = prefix + "\n" + screen_name
            let titleLable = UILabel()
            
            
            titleLable.font = UIFont.systemFontOfSize(14)
            titleLable.numberOfLines = 0
            titleLable.textAlignment = NSTextAlignment.Center
            //属性文本  可以设置字符的属性
            let attText = NSMutableAttributedString(string: cont)
            //选中要修改属性的文字， 设置属性
            let range = (cont as NSString).rangeOfString(screen_name)
            //一次添加多个属性
            attText.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(12),NSForegroundColorAttributeName:UIColor.lightGrayColor()], range: range)
            //设置属性文本给titleLable
            titleLable.attributedText = attText
            titleLable.sizeToFit()
            
            navigationItem.titleView = titleLable
        }else{
            //没有用户名称
            navigationItem.title = prefix
        }
    }
    
    
    //取消按钮点击事件
    @objc private func close(){
        //返回上一个控制器
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    //发布按钮点击事件
    @objc private func sendStatus(){
        print("点击发布")
    }
    
    //自定义一个呆占位符的textView
    private lazy var textView : CQPlaceholerTextView = {
        let tv = CQPlaceholerTextView()
        tv.font = UIFont.systemFontOfSize(18)
        //竖直方向一致有弹簧效果
        tv.alwaysBounceVertical = true
        
        tv.delegate = self
        tv.placehodler = "请输入微博内容"
        return tv
    }()
    private lazy var toolBar:UIToolbar = UIToolbar()
}
extension CQComposeController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        //有文字可用 没文字不可用
        navigationItem.rightBarButtonItem?.enabled=textView.hasText()
    }
}